package com.lottery.shadowbd.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.lottery.shadowbd.R;
import com.lottery.shadowbd.support.Constant;
import com.lottery.shadowbd.utils.LogUtils;
import com.lottery.shadowbd.utils.ToastUtil;
import com.lottery.shadowbd.widget.DownLoadingDialog;

import java.io.File;
import java.io.IOException;

public class MainActivity extends BaseActivity {

    private WebView wv_lottery;
    private ProgressBar pBar_web;

    private DownLoadingDialog mDownLoadingDialog;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);

        wv_lottery = (WebView) findViewById(R.id.wv_lottery);

        pBar_web = (ProgressBar) findViewById(R.id.pBar_web);
    }

    @Override
    protected void initData() {
        mContext = this;

        if(getIntent() != null) {
            loadWeb(getIntent().getStringExtra(Constant.KeyWebUrl));
        }
    }

    @Override
    protected void initListener() {

    }

    @Override
    public void widgetClick(View v) {

    }

    //加载网页
    private void loadWeb(String webUrl) {
        if (webUrl == null) {
            return;
        }

        wv_lottery.getSettings().setJavaScriptEnabled(true);
        wv_lottery.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); //取消滚动条白边效果
        wv_lottery.getSettings().setDefaultTextEncodingName("UTF-8");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            wv_lottery.getSettings().setMixedContentMode(wv_lottery.getSettings().MIXED_CONTENT_ALWAYS_ALLOW);  //注意安卓5.0以上的权限
        }

        wv_lottery.loadUrl(webUrl);

        wv_lottery.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                onDownloadClick(url);
            }
        });

        wv_lottery.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //拦截webviewurl跳转
                pBar_web.setVisibility(View.VISIBLE);
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }
        });

        wv_lottery.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    pBar_web.setVisibility(View.GONE);
                } else {
                    pBar_web.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message,
                                     JsResult result) {
                // TODO Auto-generated method stub
                return super.onJsAlert(view, url, message, result);
            }
        });
    }

    private void onDownloadClick(String url) {
        LogUtils.e("url=============" + url);

        mDownLoadingDialog = new DownLoadingDialog();

        mDownLoadingDialog.setmDownLoadingCallBack(new DownLoadingDialog.DownLoadingCallBack() {
            @Override
            public void onDownLoadingSucess(String apkName) {
                installApk(apkName);
            }

            @Override
            public void onDownLoadingFail(String error) {
                ToastUtil.showShort(mContext, error);
            }

            @Override
            public void onDownLoading(int num) {

            }
        });

        mDownLoadingDialog.show(getSupportFragmentManager(), "download");

        mDownLoadingDialog.downloadFile(url);
    }

    private void installApk(String apkName) {
        if(mDownLoadingDialog != null) {
            mDownLoadingDialog.dismiss();
        }

        // TODO Auto-generated method stub
        /*********下载完成，点击安装***********/
        File file = new File(Constant.RootApkPath + apkName);

        if (!file.exists()) {
            LogUtils.e("===" + Constant.RootApkPath + apkName + "不存在");
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            LogUtils.e("===" + Constant.RootApkPath + apkName + "存在");
        }

        Uri uri = Uri.fromFile(file);
        Intent intent = new Intent(Intent.ACTION_VIEW);

        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        //下载完成
        startActivity(intent);// 下载完成之后自动弹出安装界面
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //super.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        if (mDownLoadingDialog != null) {
            mDownLoadingDialog.onDialogDestroy();
            mDownLoadingDialog = null;
        }
        wv_lottery.destroy();
        super.onDestroy();
    }
}
